
package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


/**
 * E家安康-非车支付结果回写接口
 * 陶豪
 */
public  class apiPaymentResultsMsg implements  ServiceBackInvoke{
    private static final Log log= LogFactory.getLog(apiPaymentResultsMsg.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        //初始化返回参数
        JSONObject result =new JSONObject();

        //获取接口调用方式及参数
        String GetMethod=httpServletRequest.getMethod();
        log.debug("[GetMethod]:"+GetMethod);

        String inData="";
        if (GetMethod.equals("GET")){
            inData=httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]"+inData);
        }else {
            InputStreamReader reader=new InputStreamReader(httpServletRequest.getInputStream(),"UTF-8");
            BufferedReader iny=new BufferedReader(reader);
            String line;
            while ((line=iny.readLine())!=null){
                inData+=line;
            }
            log.debug("[原始Post请求参数：]"+inData);

        }
        log.debug("[调用请求信息：]"+inData)

        if (KHUtil.isNull(inData)){
            log.debug("入参为空-无法完成操作！");
            result.put("code",-2);
            result.put("message","入参为空-无法完成操作！");
            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'apiPaymentResultsMsg','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');
            return  result.toString();
        }



        try {
            //解析Json
            JSONObject inJson =JSONObject.fromObject(inData);
            def orderNo=inJson.getString("orderNo");//合作方订单申请号，系统做幂等校验
            def agencyCode=inJson.getString("agencyCode");//商户号
            def productCode=inJson.getString("productCode");//产品代码
            def businessType=inJson.getString("businessType");//业务类型
            def transTime=inJson.getString("transTime");//发送时间
            def tradeNo=inJson.getString("tradeNo");//支付流水号
            def payAmount=inJson.getString("payAmount");//已缴保费金额

            //校验参数是否必填
            if(     KHUtil.isNull(orderNo)||
                    KHUtil.isNull(agencyCode)||
                    KHUtil.isNull(productCode)||
                    KHUtil.isNull(tradeNo) ||
                    KHUtil.isNull(payAmount)

            ){
                log.debug("请求入参为空-请检查请求报文！");
                result.put("code",-2)
                result.put("message","请求入参为空-请检查请求报文！")

                def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiPaymentResultsMsg','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
                eliteBean.update(insertSQL2,'dataSource');
                return  result.toString();
            }

            JdbcTemplate jt =new JdbcTemplate(eliteBean.getDataSource());
            //查询订单号是否已经在电销存在

            String dealSql="Select orderNo from EFAMILYINFORMATION where orderNo='"+orderNo+"'";
            def dealList=eliteBean.chaxun_sql(dealSql,"dataSource");
            //存在则修改
            if (dealList.size()>0){

                //修改之前,先插入历史表
                String insertHisSql='''
                                INSERT INTO
                                 EFAMILYPAYMENTRESULTS_HIS
                                (HIS_GUID,REC_GUID,
                                ORDERNO,
                                AGENCYCODE,
                                PRODUCTCODE,
                                BUSINESSTYPE,
                                TRANSTIME,
                                TRADENO,
                                PAYAMOUNT
                                )values(
                                sysguid,
                                sysguid,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?
                               )
                                     ''';
                jt.update(insertHisSql,orderNo,agencyCode,productCode,businessType,transTime,tradeNo,payAmount);

                //更新历史表
                String updateSql='''
                                  Update
                                 EFAMILYINFORMATION
                                Set 
                                TRADENO= ?,
                                PAYAMOUNT= ?
                                where ORDERNO=? 
                                 ''';

                jt.update(updateSql,tradeNo,payAmount,orderNo);



            }else{

                log.debug("请求失败-在电销系统找不到改单号!");
                result.put("code",-1)
                result.put("message","请求失败-在电销系统找不到改单号!")
                def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiPaymentResultsMsg','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
                eliteBean.update(insertSQL2,'dataSource');
                return  result.toString();
            }
            result.put("code", 1);
            result.put("message", "处理成功！");
            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiPaymentResultsMsg','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');



        }catch(Exception e) {
            result.put("code", -1);
            result.put("message", e.getMessage());
            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,send_info,return_info,send_time,return_time) values (Sys_Guid(),'apiPaymentResultsMsg','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');
        }
        return result;
    }





}
